import store from './store-intercept/index.js'
import {addAction, subAction} from './store/actionCreators.js'

// store.subscribe(() => {
//   console.log('store state changed:', store.getState())
// })


// // 进行相应的拦截，打印调用的action，调用后state中的值的变化

// 1、基本做法
// console.log('dispatch之前  action:', addAction(10))
// store.dispatch(addAction(10))
// console.log('dispatch之后  state:', store.getState())

// console.log('dispatch之前  action:', subAction(2))
// store.dispatch(subAction(2))
// console.log('dispatch之后  state:', store.getState())


// // 2、封装简易函数
// function intercept(action){
//   console.log('dispatch之前  action:', action)
//   store.dispatch(action)
//   console.log('dispatch之后  state:', store.getState())
// }

// intercept(addAction(10))
// intercept(subAction(2))

// // 3、在2的基础上，修改原有的dispatch   monkeyPatch
// const next = store.dispatch
// function intercept(action){
//   console.log('dispatch之前  action:', action)
//   next(action)
//   console.log('dispatch之后  state:', store.getState())
// }
// store.dispatch = intercept

// store.dispatch(addAction(10))
// store.dispatch(subAction(2))

// 4、将3进行封装
// function patchLogging(store){
//   const next = store.dispatch
//   function intercept(action){
//     console.log('dispatch之前  action:', action)
//     next(action)
//     console.log('dispatch之后  state:', store.getState())
//   }
//   store.dispatch = intercept
// }
// patchLogging(store)
// store.dispatch(addAction(10))
// store.dispatch(subAction(2))

// 5、封装类似thunk的功能
// function patchThunk(store){
//   const next = store.dispatch
//   function dispatchThunk(action){
//     if (typeof action === 'function') {
//       action(store.dispatch, store.getState)
//     }else{
//       console.log('dispatch之前  action:', action)
//       next(action)
//       console.log('dispatch之后  state:', store.getState())
//     }
//   }
//   store.dispatch = dispatchThunk
// }
// patchThunk(store)
// store.dispatch(addAction(10))
// store.dispatch(subAction(2))

// function foo (dispatch, getState) {
//   store.dispatch(addAction(3))
// }
// store.dispatch(foo)

// 6、封装applyMiddleware
function patchLogging(store){
  const next = store.dispatch
  function intercept(action){
    console.log('dispatch之前  action:', action)
    next(action)
    console.log('dispatch之后  state:', store.getState())
  }
  return intercept
}

function patchThunk(store){
  const next = store.dispatch
  function dispatchThunk(action){
    if (typeof action === 'function') {
      action(store.dispatch, store.getState)
    }else{
      next(action)
    }
  }
  return dispatchThunk
}

function applyMiddleware(...middlewares){
  const newMiddlewares = [...middlewares]
  newMiddlewares.forEach(middleware =>{
    store.dispatch = middleware(store)
  })
}

applyMiddleware(patchLogging, patchThunk)
store.dispatch(addAction(10))
store.dispatch(subAction(2))